from odoo import fields, models, api, _
from odoo.exceptions import ValidationError


class WorkflowCheckWizard(models.TransientModel):
    _inherit = "workflow.check.wizard"

    qty_available = fields.Float(string="Inventory Qty")
    free_qty = fields.Float(string="Available Qty")
    incoming_qty = fields.Float(string='Incoming')
    planned_receiving_date = fields.Datetime(string='Planned Receiving Date')
    product_template_id = fields.Many2one('product.template', string='Product')

    @api.model
    def default_get(self, fields):
        res = super(WorkflowCheckWizard, self).default_get(fields)
        res.update({
            'qty_available': self.env.context.get('qty_available', 0),
            'free_qty': self.env.context.get('free_qty', 0),
            'incoming_qty': self.env.context.get('incoming_qty', 0),
            'planned_receiving_date': self.env.context.get('planned_receiving_date', 0),
            'product_template_id': self.env.context.get('product_template_id', 0),
        })
        return res

    def approval_pass(self):
        """审批通过, 计划日期必填"""
        self = self.sudo()
        if self.is_plan and not self.planned_receiving_date:
            raise ValidationError(_('Please fill in the planned receiving date'))
        sale_id = self.sb_workflow_item_id.sb_workflow_id.sale_order_id
        if self.planned_receiving_date:
            sale_id.write({'planned_receiving_date': self.planned_receiving_date})
        # JMI 销售单上传 and 下单组审批
        jmi_post = self.env['ir.config_parameter'].sudo().get_param('jmi_post')
        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        if base_url in ['http://10.150.200.2:8069', 'http://10.150.200.1:8069']:
            if jmi_post == 'enable' and sale_id and self.sb_workflow_item_id.is_jmi_upload:
                result = sale_id.action_order_jmi_post()
                if result.get('code') != 200:
                    raise ValidationError(result.get('message'))
        # EQ拦截，拦截订单状态为EQ时不能投料下单。订单确认后数量需为拼版比例的整数倍
        if sale_id and self.sb_workflow_item_id.is_engineering:
            if sale_id.special_order_type == 'eq_only':
                raise ValidationError(_('EQ order cannot be placed'))
            # SET数必须大于0
            uom_value = sale_id.product_id.uom_value_ids.filtered(lambda x: str(x.uom_id.name).upper() == 'SET').uom_value
            if uom_value <= 0:
                raise ValidationError(_('SET must be greater than 0'))
            # 判断是否是订单的整数倍
            if uom_value and sale_id.first_line.product_uom_qty % uom_value != 0:
                raise ValidationError(_('The quantity must be an integer multiple of SET'))
            if sale_id.product_id.s_disable_down_card:
                raise ValidationError(
                    _("Wait Wait!!! This %s prohibits creation of manufacturing orders'!") % sale_id.product_id.name)
        return super(WorkflowCheckWizard, self).approval_pass()
